package com.apps.Email.Service.Impl;

import cn.hutool.core.util.RandomUtil;

import com.apps.Email.Service.IMailSendService;
import com.apps.Email.config.EmailSmsConfig;
import com.apps.sannotation.constraints.Email;
import com.apps.sannotation.constraints.NoNull;
import com.apps.sannotation.constraints.StrLen;
import com.apps.saspect.ValidMethod;
import com.apps.sexctption.DataException;
import com.apps.sexctption.NullException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class MailSendServiceImpl implements IMailSendService
{

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private EmailSmsConfig smsConfig;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 验证码的缓存前缀
     */
    private final static String validCodePrifix="sms_email_code_";

    /**
     * 发送邮件
     * @param title 邮件标题
     * @param content 邮件内容
     * @param to 接受者的邮箱
     */
    @SneakyThrows
    private void sendEmail(String title,String content,String to)
    {

        //log.info("准备给[{}]发送一封主题为[{}]的邮件", to, param.getMailSubject());
        MimeMessage message = javaMailSender.createMimeMessage();
        //true表示需要创建一个multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, false);
        helper.setFrom("459082139@qq.com");
        helper.setTo(to);
        helper.setSubject(title);
        helper.setText(content,true);
        javaMailSender.send(message);
        //log.info("给[{}]发送一封主题为[{}]的邮件成功", to, param.getMailSubject());
    }

    @ValidMethod
    @Override
    public String sendValidCodeEmail(@NoNull(errMsg = "接收短信的邮箱不能为空") @Email String email)
    {
        //生成一个随机的6位数验证码
        String code= RandomUtil.randomNumbers(6);
        //发送邮件
        sendEmail("给您发送了一份邮件","您的验证码是:"+code,email);
        //发送成功则压入缓存
        redisTemplate.opsForValue().set(validCodePrifix+email,code,smsConfig.getValid_code_expire(), TimeUnit.SECONDS);
        return code;
    }

    @ValidMethod
    @Override
    public void validEmailCode(@NoNull(errMsg = "接收短信的手机号不能为空") @Email String email,
                               @StrLen(min = 6, max = 6, errMsg = "验证码必须为6位") String code)
    {
        String validCode= (String) redisTemplate.opsForValue().get(validCodePrifix+email);
        if(null == validCode)
            throw new NullException("验证码已过期!");
        if(!validCode.equals(code))
            throw new DataException("验证码错误");
        //删除验证码
        redisTemplate.delete(validCodePrifix+email);
    }


}
